package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Callable;

@Component
public class AccessFilter extends ZuulFilter {
    //指定过滤器的类型   "pre"   "routes"   "post"    "error"
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //指定过滤器添加的位置序号
    @Override
    public int filterOrder() {
        return 6;
    }
    // 判断针对当前这次请求， 是否要执行过滤代码
    // 如果请求 item-service  执行全选判断
    // 如果请求 user  执行全选判断
    @Override
    public boolean shouldFilter() {
        //获得正在调用的服务的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {

        //得到request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接受token参数
        String token = request.getParameter("token");
        //如果token参数不存在,阻止继续调用,直接返回提示
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);
            //返回登录提示
            //
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("not login,没有登录!").toString();
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;    //返回任何数据都无效
    }
}
